﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace StyleMVVM.View
{
	public class RegionCollection : ObservableCollection<Region>
	{
		private WeakReference elementReference;

		public FrameworkElement Element
		{
			get
			{
				if (elementReference != null)
				{
					return elementReference.Target as FrameworkElement;
				}

				return null;
			}
			set
			{
				if (value != null)
				{
					elementReference = new WeakReference(value);
				}
				else
				{
					elementReference = null;
				}
			}
		}

		protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
		{
			if (e.OldItems != null)
			{
				foreach (Region oldRegion in e.OldItems)
				{
					oldRegion.Element = null;
				}
			}

			if (e.NewItems != null)
			{
				foreach (Region newRegion in e.NewItems)
				{
					newRegion.Element = Element;
				}
			}

			bool foundMain = false;

			for (int i = 0; i < this.Count; i++)
			{
				if (this[i].IsContainerMaster)
				{
					foundMain = true;
					break;
				}
			}

			if (!foundMain && Count > 0)
			{
				this[0].IsContainerMaster = true;
			}

			base.OnCollectionChanged(e);
		}
	}
}